using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using PlugIn;
using System.Reflection;


namespace MyEditor
{
    public partial class Form1 : Form,IPluginHost
    {
        List<Mypoint> lines1 = new List<Mypoint>();
        List<Mypoint> lines2 = new List<Mypoint>();
        int[,] tempLab;
        int[,] objectLab;
        Kmeans k1;
        int state = 0; //0:watershed,1:region merge, 2:GraphCut,3 region Labelling,4:region splite,5:region watersheds,7:show lab,8,9:region hierarchy
                        //10:select in the structure
        List<Mypoint> regionMerge = new List<Mypoint>();
        List<Mypoint> regionSplit = new List<Mypoint>();
        Mypoint split = new Mypoint();
        Bitmap copyofpic2;
        Mypoint pointToWatershed;
        Mypoint regionTolabel;
        Mypoint regionTohierarchy;
        string selected, selected2;
        List<Mylabel> labelsList = new List<Mylabel>();
        Bitmap segedBitmap;
        Bitmap unselectedBitmap;
        bool seged = false;
        string selectedLabText;


        private IPlugin[] ipi;


        public Form1()
        {
            InitializeComponent();

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {




        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            int k=0;
            try
            {
                k = Int32.Parse(textBox1.Text.ToString());
            }
            catch
            {
                MessageBox.Show("Input Color group number");
            }

            if (k >= 2 && k <= 64)
            {
                button1.Enabled = false;
                textBox1.Enabled = false;
                button1.Enabled = false;
                Bitmap tempPic = new Bitmap(pictureBox2.Image);
                k1 = new Kmeans((Bitmap)pictureBox2.Image, k);
                k1.DokMeans();
                Watershed t = new Watershed(k1.getResult(), k,tempPic);
                t.DoWaterShed();
                pictureBox2.Image = t.GetSegPic();
                tempLab = new int[pictureBox2.Image.Width, pictureBox2.Image.Height];
                tempLab = t.segMap();
                pictureBox2.Refresh();
                button5.Enabled = true;
                button3.Enabled = true;
                this.seged = true;
            }
            else
            {
                MessageBox.Show("Color group number should be >=2 and <=64");
            }
        }

        /*public Bitmap imagCut(int[,] lab, Bitmap tpic)
        {

            foreach (Mypoint p in lines)
            {
                int hight = lab[p.x, p.y];
                if (hight == -1000 || hight == 0) continue;
                for (int i = 0; i < pictureBox1.Image.Width; i++)
                    for (int j = 0; j < pictureBox1.Image.Height; j++)
                        if (lab[i, j] == hight)
                            lab[i, j] = -1000;
            }


            Bitmap pic = new Bitmap(tpic);
            unsafe
            {
                BitmapData data = pic.LockBits
                    (new Rectangle(0, 0, pic.Width, pic.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

                byte* imgPtr = (byte*)(data.Scan0);

                for (int j = 0; j < data.Height; j++)
                {
                    for (int i = 0; i < data.Width; i++)
                    {
                        if (lab[i, j] != -1000)
                            imgPtr[0] = imgPtr[1] = imgPtr[2] = 0;

                        imgPtr += 3;
                    }
                    imgPtr += data.Stride - data.Width * 3;
                }
                pic.UnlockBits(data);
            }
            lines.Clear();
            return pic;
        }*/

        private void Form1_Load(object sender, EventArgs e)
        {
           
            button1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            loadPlugins();


        }

        private void loadPlugins()
        {
            string path = Application.StartupPath;
            string[] pluginFiles = Directory.GetFiles(path, "*.dll");
            ipi = new IPlugin[pluginFiles.Length];

            for (int i = 0; i < pluginFiles.Length; i++)
            {
                string args = pluginFiles[i].Substring(
                    pluginFiles[i].LastIndexOf("\\") + 1,
                    pluginFiles[i].IndexOf(".dll") -
                    pluginFiles[i].LastIndexOf("\\") - 1);

                Type ObjType = null;
                //IPlugin ipi;
                // load the dll
                try
                {
                    // load it
                    Assembly ass = null;
                    ass = Assembly.Load(args);
                    if (ass != null)
                    {
                        ObjType = ass.GetType(args + ".MyOp");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                try
                {
                    // OK Lets create the object as we have the Report Type
                    if (ObjType != null)
                    {
                        ipi[i] = (IPlugin)Activator.CreateInstance(ObjType);
                        ipi[i].Host = this;
                        //Console.WriteLine("ipi.Add(1,2)=" + ipi[i].Add(1,2));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }


        }

        public bool Register(IPlugin ipi)
        {

            plugInsToolStripMenuItem.DropDown.Items.Add(new ToolStripMenuItem(ipi.Name, null, new EventHandler(NewLoad)));


            //MenuItem mn = new MenuItem(ipi.Name, new EventHandler(NewLoad));

            Console.WriteLine("Registered: " + ipi.Name);
            //menuItem1.MenuItems.Add(mn);
            return true;
        }

        private void NewLoad(object sender, System.EventArgs e)
        {
            ToolStripMenuItem mn = (ToolStripMenuItem)sender;

            for (int i = 0; i < ipi.Length; i++)
            {
                string strType = mn.Text;
                if (ipi[i] != null)
                {
                    if (ipi[i].Name == strType)
                    {
                        pictureBox2.Image = ipi[i].Do((Bitmap)pictureBox2.Image, labelsList, selectedLabText);
                        break;
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox2.Text.Equals(""))
            {
                MessageBox.Show("Input the Object name");
            }
            else
            {
                
                objectLab = new int[pictureBox1.Width, pictureBox1.Height];
                for (int i = 0; i < pictureBox1.Width; i++)
                    for (int j=0; j < pictureBox1.Height; j++)
                    {
                        objectLab[i, j] = tempLab[i, j];

                    }

                Mylabel tl = new Mylabel();
                tl.name = 'O'+textBox2.Text;
                button2.Enabled = false;
                regionsTograph rt1 = new regionsTograph(tempLab, lines1, lines2, k1.getResult2(), pictureBox1.Width, pictureBox1.Height, (Bitmap)pictureBox1.Image);
                node S = new node();
                S.name = -1000;
                S.tree = 1;
                S.parent = null;
                node T = new node();
                T.name = -2000;
                T.tree = 2;
                T.parent = null;
                GraphCut gc = new GraphCut(rt1.getNodes(), rt1.getEdges(), S, T);
                gc.doCut();
                List<node> s;
                s = gc.getStree();
                List<node> t;
                t = gc.getTtree();
                for (int i = 0; i < pictureBox1.Width; i++)
                    for (int j = 0; j < pictureBox1.Height; j++)
                    {
                        foreach (node p in s)
                            if (tempLab[i, j] == p.name)
                            {
                                tl.pixels.Add(new Mypoint(i, j));
                                objectLab[i, j] = -1000;
                                ((Bitmap)pictureBox2.Image).SetPixel(i, j, ((Bitmap)pictureBox1.Image).GetPixel(i, j));
                            }
                        foreach (node q in t)
                            if (tempLab[i, j] == q.name)
                            {
                                objectLab[i, j] = -2000;
                                ((Bitmap)pictureBox2.Image).SetPixel(i, j, Color.Green);
                            }

                    }
                button2.Enabled = true;
                pictureBox2.Refresh();
                labelsList.Add(tl);
                this.treeview();
                lines1.Clear();
                lines2.Clear();

            }
                       

        }

        public void drawIt(List<Mypoint> line, int seed)
        {
            if (seed == 0)
            {
                Bitmap pic = (Bitmap)pictureBox2.Image;
                foreach (Mypoint p in line)
                {
                    pic.SetPixel(p.x, p.y, Color.FromArgb(255, 0, 0));
                    if (!lines1.Contains(p))
                        lines1.Add(p);
                 
                }
                pictureBox2.Refresh();
            }
            else
            {
                Bitmap pic = (Bitmap)pictureBox2.Image;
                foreach (Mypoint p in line)
                {
                    //pic.SetPixel(p.x, p.y, Color.FromArgb(0,0,255));
                    pic.SetPixel(p.x, p.y, Color.Yellow);
                    if (!lines2.Contains(p))
                        lines2.Add(p);
                   
                }
                pictureBox2.Refresh();

            }
        }

        private void button1_MouseMove(object sender, MouseEventArgs e)
        {


        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {

        }

        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (state == 8)
            {
                regionTohierarchy.x = e.X;
                regionTohierarchy.y = e.Y;
            }
            if (state == 3)
            {
                regionTolabel.x = e.X;
                regionTolabel.y = e.Y;
            }
            if (state == 7)
            {
                label4.Text = tempLab[e.X, e.Y].ToString();

            }
            if (state == 5)
            {
                pointToWatershed.x = e.X;
                pointToWatershed.y = e.Y;
            }
            if (state==2)
            {
                if (e.Button == MouseButtons.Left)
                {

                    List<Mypoint> points = new List<Mypoint>();

                    Mypoint t = new Mypoint(e.X, e.Y);
                    if (!points.Contains(t))
                        points.Add(t);
                    this.drawIt(points, 0);
                }



                if (e.Button == MouseButtons.Right)
                {

                    List<Mypoint> points = new List<Mypoint>();

                    Mypoint t = new Mypoint(e.X, e.Y);
                    if (!points.Contains(t))
                        points.Add(t);



                    this.drawIt(points, 1);
                }
            }
            if (state == 1)
            {
                if (e.Button == MouseButtons.Left)
                {
                    Mypoint temp = new Mypoint(e.X, e.Y);
                    if (regionMerge.Count < 2)
                    {
                        regionMerge.Add(temp);
                    }
                }
            }
            if (state == 4)
            {
                if (e.Button == MouseButtons.Right)
                {
                    split.x = e.X;
                    split.y = e.Y;
                }
            }
            
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            selectedLabText = e.Node.Text;
            if (state == 10)
            {
                foreach (Mylabel ml in labelsList)
                {
                    if (ml.name.Equals(e.Node.Text))
                    {
                        unselectedBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
                        unselectedBitmap =(Bitmap) pictureBox2.Image.Clone();
                        foreach (Mypoint mp in ml.pixels)
                        {
                            ((Bitmap)pictureBox2.Image).SetPixel(mp.x, mp.y, Color.Red);
                        }
                    }
                }
                
            }
            if (state==8)
            {
                selected = e.Node.Text;
                state = 9;
                label6.Text = "select a child";
            }
            else
            {
                if (state == 9)
                {
                    selected2 = e.Node.Text;
                }
            }
            

        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            state = 1;
            button4.Enabled = true;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            segedBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            segedBitmap = (Bitmap)((Bitmap)pictureBox2.Image).Clone();
            state = 2;
            button5.Enabled = false;
            button2.Enabled = true;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            int lab0 = tempLab[regionMerge[0].x, regionMerge[0].y];
            int lab1 = tempLab[regionMerge[1].x, regionMerge[1].y];
            for (int i=0;i<pictureBox1.Image.Width;i++)
                for (int j = 0; j < pictureBox1.Image.Height; j++)
                {
                    //Bitmap pic = (Bitmap)pictureBox2.Image;
                    //Color c = pic.GetPixel(regionMerge[0].x, regionMerge[0].y);

                    if (tempLab[i, j] == lab1)
                    {
                        tempLab[i, j] = lab0;
                        //pic.SetPixel(i, j, c);
                    }
                }
            Bitmap pic = (Bitmap)pictureBox2.Image;
            Bitmap pic1 = (Bitmap)pictureBox1.Image;

            for (int i=2;i<pictureBox1.Image.Width-2;i++)
                for (int j = 2; j < pictureBox1.Image.Height-2; j++)
                {
                    if (tempLab[i, j] == 0)
                    {
                        if ((tempLab[i, j+2] == tempLab[i, j-2])&&(tempLab[i,j+2]==lab0))
                        {
                            tempLab[i, j] = tempLab[i, j+2];
                            pic.SetPixel(i, j, pic1.GetPixel(i, j));
                        }
                    }
                }
            for (int j = 2; j < pictureBox1.Image.Height-2; j++)
                for (int i=2;i<pictureBox1.Image.Width-2;i++)
                    if (tempLab[i, j] == 0)
                    {
                        if ((tempLab[i - 2, j] == tempLab[i + 2, j]) && (tempLab[i + 2, j] == lab0))
                        {
                            tempLab[i, j] = tempLab[i + 2, j];
                            pic.SetPixel(i, j, pic1.GetPixel(i, j));
                        }

                    }
            pictureBox2.Refresh();
      
    
            button3.Enabled = true;
            
            regionMerge.Clear();
        }

       

        private void exitToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            state = 4;
            copyofpic2 = (Bitmap)pictureBox2.Image.Clone();
        }

        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
        {
            if (state == 2)
            {
                if (e.Button == MouseButtons.Left)
                {

                    List<Mypoint> points = new List<Mypoint>();

                    Mypoint t = new Mypoint(e.X, e.Y);
                    if (!points.Contains(t))
                        points.Add(t);
                    this.drawIt(points, 0);
                }



                if (e.Button == MouseButtons.Right)
                {

                    List<Mypoint> points = new List<Mypoint>();

                    Mypoint t = new Mypoint(e.X, e.Y);
                    if (!points.Contains(t))
                        points.Add(t);



                    this.drawIt(points, 1);
                }
            }
            if (state == 4)
            {
                if (e.Button == MouseButtons.Left)
                {
                    if (!((e.X < 0) || (e.Y < 0) || (e.X >= pictureBox1.Width) || (e.Y >= pictureBox1.Height)))
                    {
                        Mypoint temp = new Mypoint(e.X, e.Y);
                        regionSplit.Add(temp);
                        try
                        {

                            ((Bitmap)pictureBox2.Image).SetPixel(e.X, e.Y, Color.Red);
                        }
                        catch
                        {

                        }
                    }
                }

            }
            
            pictureBox2.Refresh();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            int lab = tempLab[split.x, split.y];
            Queue<Mypoint> temp = new Queue<Mypoint>();
            List<Mypoint> pl = new List<Mypoint>();
            temp.Enqueue(split);
            pl = ngb(temp,pl);
            int curMaxLab=0;
            foreach (int t in tempLab)
            {
                if (curMaxLab < t)
                    curMaxLab = t;
            }
            pictureBox2.Image = (Bitmap)copyofpic2.Clone();
            foreach (Mypoint p in regionSplit)
            {
                if (tempLab[p.x, p.y] == lab)
                {
                    tempLab[p.x, p.y] = 0;
                    ((Bitmap)pictureBox2.Image).SetPixel(p.x, p.y, Color.Black);
                }
            }

            foreach (Mypoint p in pl)
            {
                tempLab[p.x, p.y] = curMaxLab + 1;
                ((Bitmap)pictureBox2.Image).SetPixel(p.x, p.y, ((Bitmap)pictureBox1.Image).GetPixel(p.x, p.y));
            }

            temp.Clear();
            pl.Clear();
            pictureBox2.Refresh();
           
        }

        List<Mypoint> ngb(Queue<Mypoint> pl,List<Mypoint> ngbl)
        {
            if (pl.Count == 0)
            {
                return ngbl;
            }
            
            Mypoint p = pl.Dequeue();
            ngbl.Add(p);
            bool ok = true;
            for (int i = p.x - 1; i <= p.x + 1; i++)
                for (int j = p.y - 1; j <= p.y + 1; j++)
                {
                    
                    Mypoint t = new Mypoint(i, j);
                    if (regionSplit.Contains(t))
                    {
                        ok = false;
                    }
                }
            if (ok)
            {
                for (int i = p.x - 1; i <= p.x + 1; i++)
                    for (int j = p.y - 1; j <= p.y + 1; j++)
                    {
                        if ((i<0)||(j<0)||(i==pictureBox1.Width)||(j==pictureBox1.Height))
                            continue;
                        if ((i == p.x) && (j == p.y))
                            continue;
                        if (tempLab[i, j] == tempLab[split.x, split.y])
                        {
                            Mypoint t = new Mypoint(i, j);
                            if ((!pl.Contains(t)) && (!ngbl.Contains(t)))
                            {
                                pl.Enqueue(t);
                                
                            }
                        }
                    }
            }
            return ngb(pl,ngbl);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            state = 5;
            textBox1.Enabled = true;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int lab = tempLab[pointToWatershed.x, pointToWatershed.y];
            List<Mypoint> tl = new List<Mypoint>();
            int minX =int.MaxValue, minY = int.MaxValue, maxX = -1, maxY = -1;
            for (int i= 0;i<pictureBox1.Image.Width;i++)
                for (int j=0;j<pictureBox1.Image.Height;j++)
                    if (tempLab[i, j] == lab)
                    {
                        tl.Add(new Mypoint(i, j));
                        if (i < minX)
                            minX = i;
                        if (j < minY)
                            minY = j;
                        if (i > maxX)
                            maxX = i;
                        if (j > maxY)
                            maxY = j;
                    }
            Bitmap tempPic = new Bitmap(maxX - minX + 1, maxY - minY + 1);
            foreach (Mypoint p in tl)
            {
                tempPic.SetPixel(p.x - minX, p.y - minY, ((Bitmap)pictureBox1.Image).GetPixel(p.x, p.y));
            }
            //pictureBox3.Image = tempPic;
            int k = 0;
            try
            {
                k = Int32.Parse(textBox1.Text.ToString());
            }
            catch
            {
                MessageBox.Show("Input Color group number");
            }
            if (k < 5)
                k = 5;
            Bitmap tempPic2 = new Bitmap(tempPic);
            Kmeans km = new Kmeans(tempPic, k);
            km.DokMeans();
            Watershed t = new Watershed(km.getResult(), k, tempPic2);
            t.DoWaterShed();
            int[,] labMap= new int[tempPic.Width, tempPic.Height];
            labMap = t.segMap();
            int maxLab=0;
            for (int i = 0; i < pictureBox2.Width; i++)
                for (int j = 0; j < pictureBox2.Height; j++)
                {
                    if (tempLab[i, j] > maxLab)
                        maxLab = tempLab[i, j];
                }
            foreach (Mypoint p in tl)
            {
                if (labMap[p.x - minX, p.y - minY] == 0)
                    tempLab[p.x, p.y] = 0;
                else
                    tempLab[p.x, p.y] =maxLab + labMap[p.x - minX, p.y - minY]-1;
            }
            //pictureBox3.Image = t.GetSegPic();
            for (int i = 0; i < pictureBox2.Width; i++)
                for (int j = 0; j < pictureBox2.Height; j++)
                {
                    if (tempLab[i, j] == 0)
                    {
                        ((Bitmap)pictureBox2.Image).SetPixel(i, j, Color.Black);
                    }
                }
            pictureBox2.Refresh();


            
        }

        private void button10_Click(object sender, EventArgs e)
        {
            state = 7;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            state = 3;
        }

        private void button13_Click(object sender, EventArgs e)
        {
            int lab = tempLab[regionTolabel.x,regionTolabel.y];
            Mylabel temp = new Mylabel();
            temp.name = "S" + lab.ToString();
            for (int i=0;i<pictureBox1.Width;i++)
                for(int j=0;j<pictureBox1.Height;j++)
                    if (tempLab[i, j] == lab)
                    {
                        temp.pixels.Add(new Mypoint(i, j));
                    }
            
            labelsList.Add(temp);
           /* TreeNode tempnode = new TreeNode();
            tempnode.Name = temp.name;
            treeView1.Nodes.Add(tempnode);
            
            */
            this.treeview();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            Mylabel tparent = null;
            Mylabel tchild = null;
            foreach(Mylabel tLabel2 in labelsList)
            {
                if (tLabel2.name == selected)
                {
                    tparent = tLabel2;
                    break;
                }
            }
            foreach (Mylabel tLabel2 in labelsList)
            {
                if (tLabel2.name == selected2)
                {
                    tchild = tLabel2;
                    break;
                }
            }

           /* int lab = tempLab[regionTohierarchy.x,regionTohierarchy.y];
            Mylabel temp = new Mylabel();
            temp.name = "L" + lab.ToString();
            for (int i=0;i<pictureBox1.Width;i++)
                for(int j=0;j<pictureBox1.Height;j++)
                    if (tempLab[i, j] == lab)
                    {
                        temp.pixels.Add(new Mypoint(i, j));
                    }
            labelsList.Add(temp);*/
            tchild.parent = tparent;
            tparent.children.Add(tchild);

            /*TreeNode tempnode = new TreeNode();
            tempnode.Name = temp.name;
            treeView1.Nodes.Add(tempnode);
            labelsList.Add(temp);
            TreeNode tempnode2;
            foreach (TreeNode tNode in treeView1.Nodes)
            {
                if (tNode.Name == selected)
                {
                    tempnode2 = tNode;
                    break;
                }
            }
            treeView1.Nodes.*/
            this.treeview();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            state = 8;
            label6.Text = "select parent";
        }

        private void treeview()//only support 3 levels now
        {
            treeView1.Nodes.Clear();
            //List<Mylabel> labelsList2 = new List<Mylabel>();
            //labelsList.cop
            foreach (Mylabel ml in labelsList)
            {
                if (ml.parent == null)
                {
                    TreeNode tn = new TreeNode(ml.name);
                    treeView1.Nodes.Add(tn);
                }
            }
            foreach (Mylabel ml in labelsList)
            {
                if (ml.parent != null)
                {
                    if (ml.parent.parent == null)
                    {
                        int index = 0;
                        foreach (TreeNode tr in treeView1.Nodes)
                        {
                            if (tr.Text.Equals(ml.parent.name))
                                index = tr.Index;
                        }
                        TreeNode tn = new TreeNode(ml.name);
                        treeView1.Nodes[index].Nodes.Add(tn);



                    }

                    else
                    {
                        int index = 0;
                        foreach (TreeNode tr in treeView1.Nodes)
                        {
                            if (tr.Text.Equals(ml.parent.parent.name))
                                index = tr.Index;
                        }
                        int index2 = 0;
                        foreach (TreeNode tr in treeView1.Nodes[index].Nodes)
                        {
                            if (tr.Text.Equals(ml.parent.name))
                                index2 = tr.Index;

                        }
                        TreeNode tn = new TreeNode(ml.name);
                        treeView1.Nodes[index].Nodes[index2].Nodes.Add(tn);

                    }
                }
            }


        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fn = openFileDialog1.FileName;
                if (fn.Length != 0)
                {
                    try
                    {
                        pictureBox1.Image = new Bitmap(fn);
                        pictureBox2.Image = new Bitmap(fn);
                    }
                    catch
                    {
                        MessageBox.Show("File open error!");
                    }
                    string[] fns = fn.Split(new Char[] { '.'});
                    string fn1= fns[0] + ".mda";
                    if (File.Exists(fn1))
                    {
                        MessageBox.Show("This Image file has a metadata file");
                        try
                        {
                            IFormatter formatter = new BinaryFormatter();
                            Stream stream = new FileStream(fn1, FileMode.Open, FileAccess.Read, FileShare.Read);
                            SegMap segmapObj = (SegMap)formatter.Deserialize(stream);
                            labelsList = (List<Mylabel>)formatter.Deserialize(stream);
                            stream.Close();
                            tempLab = segmapObj.lab;
                            seged = true;
                            for (int i = 0; i < pictureBox1.Width; i++)
                                for (int j = 0; j < pictureBox1.Height; j++)
                                {
                                    if (tempLab[i, j] == 0)
                                        ((Bitmap)pictureBox2.Image).SetPixel(i, j, Color.Black);
                                }
                            this.treeview();

                        }
                        catch
                        {
                            MessageBox.Show("Open the Metadata file error");
                        }

                    }
                    else
                    {
                        MessageBox.Show("This Image file doesn't have a metadata file");
                    }
                    

                    
                }

            }
            
        }

        private void button15_Click(object sender, EventArgs e)
        {
            pictureBox2.Image = (Bitmap)segedBitmap.Clone();
            lines1.Clear();
            lines2.Clear();
            button5.Enabled = true;

        }

        private void button16_Click(object sender, EventArgs e)
        {
            state = 10;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            try
            {
                pictureBox2.Image = (Bitmap)unselectedBitmap.Clone();

            }
            catch
            {

            }
            treeView1.SelectedNode = null;
        }

        private void treeView1_Click(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fn = saveFileDialog1.FileName;
                if (fn.Length != 0)
                {
                    try
                    {
                        ((Bitmap)pictureBox1.Image).Save(fn);
                    }
                    catch
                    {
                        MessageBox.Show("Save File Error");
                    }
                }

                if (seged == true)
                {
                    try
                    {
                        string[] fns = fn.Split(new Char[] { '.' });
                        string fn1 = fns[0] + ".mda";
                        IFormatter formatter = new BinaryFormatter();
                        Stream stream = new FileStream(fn1, FileMode.Create, FileAccess.Write);
                        SegMap smap = new SegMap(pictureBox1.Width, pictureBox1.Height);
                        smap.lab = tempLab;
                        formatter.Serialize(stream, smap);
                        formatter.Serialize(stream, labelsList);
                        stream.Close();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("creat metadate file error,"+ex.Message);
                    }


                }
                else
                {

                }
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            pictureBox2.Image = (Bitmap)pictureBox1.Image.Clone();
            seged = false;

        }

        private void button19_Click(object sender, EventArgs e)
        {
            foreach (Mylabel ml in labelsList)
                {
                    if (ml.name.Equals(selectedLabText))
                    {
                        unselectedBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
                        unselectedBitmap =(Bitmap) pictureBox2.Image.Clone();
                        foreach (Mypoint mp in ml.pixels)
                        {
                            int grey = (((Bitmap)pictureBox2.Image).GetPixel(mp.x,mp.y).R+((Bitmap)pictureBox2.Image).GetPixel(mp.x,mp.y).G
                                +((Bitmap)pictureBox2.Image).GetPixel(mp.x,mp.y).B)/3;
                            ((Bitmap)pictureBox2.Image).SetPixel(mp.x, mp.y,Color.FromArgb(grey,grey,grey));
                        }
                    }
                }
        }

        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                pictureBox2.Image = (Bitmap)unselectedBitmap.Clone();

            }
            catch
            {

            }
            
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

    }

    /*[Serializable]
    public struct Mypoint
    {
        public int x;
        public int y;
        public Mypoint(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }*/
}
